<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          流程类型:
          <NSelect :options="parentCodeList" placeholder="请选择流程类型" clearable style="width: 200rem" label-field="name"
            value-field="value" v-model:value="paginationReactive.functionCode" :render-option="renderOption" filterable
             />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getDraftsList())">
            查询
          </NButton>
        </NSpace>
        <NSpace>
          <!-- <NButton type="primary" style="width: 120rem" @click="submitOrDelect(true)" :disabled="tableData?.length == 0"
            ghost>
            批量提交审批
          </NButton> -->
          <NButton type="error" style="width: 120rem;" @click="submitOrDelect(false)" :disabled="tableData?.length == 0"
            ghost>
            批量删除
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" :row-key="rowKeys" :checked-row-keys="dataListSelections"
        @update:checked-row-keys="selectionChangeHandle" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="deleteVisible" @close="deleteVisible = false">
    <VDialogContent @close="deleteVisible = false" @submit="deleteDraft" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定删除吗？
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="submitVisible" @close="submitVisible = false">
    <VDialogContent @close="submitVisible = false" @submit="submitDraft" title="提交提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定提交吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { h, reactive, onMounted, ref, type VNode, watch, onDeactivated } from 'vue'
import { NSpace, NButton, NDataTable, NPagination, NSelect, useMessage, NModal, NTooltip } from 'naive-ui'
import type { DataTableColumns, SelectOption } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { UserModel } from '@/api/userCenter'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useViewerStore } from '@/views/OA/Common/store'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKeys: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    fixed: 'left',
    width: 30,
    align: useStore.isCenter
  },
  {
    title: '流程类型',
    key: 'codeName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '流程备注',
    key: 'remark',
    width: 300,
    align: useStore.isCenter
  },
  {
    title: '申请时间',
    key: 'createTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 100,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            const path = jumpRouterList.value.find((it: any) => it.code == row.code)?.routeTwo
            if (path) router.push({ path, query: { id: row.resourceId as never } })
            else message.error('功能正在开发中')
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          color: useStore.color['delete'],
          onClick: () => {
            draftsId.value = [row.id]
            isFlat.value = false
            deleteVisible.value = true
          }
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  functionCode: null, //类型
  onChange: (page: number) => {
    paginationReactive.page = page
    getDraftsList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getDraftsList()
  }
})
// select的Tooltip
const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) => {
  return h(NTooltip, { style: { backgroundColor: '#e1e1e1' } }, {
    trigger: () => node,
    default: () => option.name
  })
}
// 审批
const submitOrDelect = async (flat: any) => {
  isFlat.value = true
  if (dataListSelections.value.length && flat) return (submitVisible.value = true)
  if (dataListSelections.value.length && !flat) return (deleteVisible.value = true)
  message.error('请最少选择一项数据')
}
// table的key选择
const dataListSelections: any = ref([])
function selectionChangeHandle(val: any) {
  dataListSelections.value = val
}
// 删除草稿
const isFlat = ref(false)
const draftsId: any = ref()
const deleteVisible = ref(false)
const deleteDraft = async () => {
  deleteVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'draftsSelete',
    override: {
      data: isFlat.value ? dataListSelections.value : draftsId.value
    }
  })
  if (error) return message.error(error.message), (tableLoading.value = false)
  if (res.code != 0) return message.error(res.msg), (tableLoading.value = false)
  message.success('删除成功')
  dataListSelections.value = []
  draftsId.value = []
  getDraftsList()
}
// 提交申请
const submitVisible = ref(false)
const submitDraft = async () => {
  submitVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'draftsSubmit',
    override: {
      data: isFlat.value ? dataListSelections.value : draftsId.value
    }
  })
  if (error) return message.error(error.message), (tableLoading.value = false)
  if (res.code != 0) return message.error(res.msg), (tableLoading.value = false)
  message.success('提交成功')
  dataListSelections.value = []
  draftsId.value = []
  getDraftsList()
}
//流程类型
const parentCodeList: any = ref([])
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'getWorkFlowFunctionCodeList',
  })
  if (error) return
  if (res.code != 0) return
  parentCodeList.value = res.data
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getDraftsList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'draftsList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        functionCode: paginationReactive.functionCode
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}
//获取需要跳转的路由
const jumpRouterList: any = ref([])
const getJumpRouterList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'getJumpRoute'
  })
  if (error) return message.error(error.message)
  jumpRouterList.value = res.data
}

onMounted(() => {
  getJumpRouterList()
  getFunction()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getDraftsList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  () => {
    if (route.path == '/OA/UserCenter/Drafts') {
      getDraftsList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
